package com.common.config;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.client.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class RestTemplateConfig {
	private static final Logger log = Logger.getLogger(RestTemplateConfig.class);

	@Bean
	public RestTemplate restTemplate(ClientHttpRequestFactory factory) {

		RestTemplate restTemplate = new RestTemplate(factory);
		restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());

		restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {

			@Override
			public ClientHttpResponse intercept(HttpRequest arg0, byte[] arg1, ClientHttpRequestExecution arg2)
					throws IOException {
				if (null != arg0)
					log.info(arg0.getURI());

				return arg2.execute(arg0, arg1);
			}
		});
		return restTemplate;
	}

	@Bean
	public ClientHttpRequestFactory clientHttpRequestFactory() {

		// HttpComponentsClientHttpRequestFactory factory = new
		// HttpComponentsClientHttpRequestFactory();
		// factory.setHttpClient(HttpsClientPoolThread.builder().createSSLClientDefault());
		// //这里是使用了自定义的一个HttpsClientPoolThread线程池单例 以后有机会会单独写文章展示其配置内容,
		// 大家可以先使用默认的HttpClients.createDefault()进行配置,或自定义线程池;
		// factory.setConnectTimeout(10000);
		// factory.setReadTimeout(10000);
		// factory.setConnectionRequestTimeout(200);

		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setReadTimeout(50000); // ms
		factory.setConnectTimeout(15000); // ms
		return factory;
	}

	class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
		public WxMappingJackson2HttpMessageConverter() {
			List<MediaType> mediaTypes = new ArrayList<>();
			mediaTypes.add(MediaType.TEXT_PLAIN);
			setSupportedMediaTypes(mediaTypes);// tag6
		}
	}
}
